package com.example.backend.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.backend.api.common.Result;
import com.example.backend.api.entity.Dept;
import com.example.backend.api.mapper.DeptMapper;
import com.example.backend.api.service.DeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xwyzsn
 * @since 2023-03-07
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    public Result getAll() {
        return Result.success(deptMapper.selectList(null));
    }

    public Result updateDept(Integer id, String name) {
        UpdateWrapper<Dept> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("dept_id", id);
        updateWrapper.set("name", name);
        int res = deptMapper.update(null, updateWrapper);
        return Result.success(res);
    }

    public Result addDept(String name, Integer deptId) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dept_id", deptId);
        if (deptMapper.selectOne(queryWrapper) != null) {
            return Result.fail("部门已存在");
        }
        Dept dept = new Dept();
        dept.setName(name);
        dept.setDeptId(deptId);
        int res = deptMapper.insert(dept);
        return Result.success(res);
    }

}
